<template>
  <a-modal :visible="visible" centered :maskClosable="false" width="80%" title="新增临时任务执行" @cancel="$emit('cancel', !visible)" :okButtonProps="{
    props: {
      loading: formLoading
    },
    on: {
      click: onSubmit
    }
  }" :cancelButtonProps="{
    props: {
      loading: formLoading
    },
    on: {
      click: onCancel
    }}">
    <a-form-model class="fold-form" :model="queryParam" ref="form" :label-col="{span:'4' }" :wrapper-col="{span:'20' }" :rules="rules">
      <FoldForm v-model="visible">
        <a-col :md="6" :sm="24">
          <a-form-model-item label="执行时间" prop="startTime">
            <a-date-picker placeholder="请选择执行时间" v-model="queryParam.startTime" />
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item label="任务名称" prop="taskName">
            <a-input placeholder="请输入任务名称" v-model="queryParam.taskName" :maxLength="20" />
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item label="设备编号" prop="deviceCode">
            <a-select v-model="queryParam.deviceCode" @change="deviceSelectChange"></a-select>
            <!-- <DeviceSelect v-model="queryParam.deviceCode" @change="deviceSelectChange" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item label="设备型号" prop="deviceModel">
            <a-input placeholder="请输入" v-model="queryParam.deviceModel" disabled />
          </a-form-model-item>
        </a-col>
        <!--         <a-col :md="6" :sm="24">
          <a-form-model-item label="设备名称" prop="deviceName">
            <a-input placeholder="请输入设备名称" v-model="queryParam.deviceName" />
          </a-form-model-item>
        </a-col> -->
        <a-col :md="6" :sm="24">
          <a-form-model-item label="执行人" prop="executorName">
            <a-select v-model="queryParam.executorName" :placeholder="'请选择执行人'" :showCode="false"></a-select>

            <!-- <UserSelect v-model="queryParam.executorName" :placeholder="'请选择执行人'" :showCode="false" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item label="优先级" prop="taskLevel">
            <a-select v-model="queryParam.taskLevel" typeName="优先级" placeholder="请选择优先级"></a-select>

            <!-- <DictionarySelect v-model="queryParam.taskLevel" typeName="优先级" placeholder="请选择优先级" /> -->
          </a-form-model-item>
        </a-col>
      </FoldForm>
      <a-col>
        <a-space direction="vertical" class="block">
          <a-table bordered size="middle" :pagination="false" rowKey="index" :dataSource="form.devicePart">
            <!-- 为空的输入框修改显示状态 -->
            <a-table-column title="序号">
              <template #default="text, params, index">{{ index + 1 }}</template>
            </a-table-column>
            <a-table-column title="项目名称">
              <template #default="text, params">
                <a-form-item hasFeedback :validate-status="params.projectName === '' ? 'warning' : ''">
                  <a-input v-model="params.projectName" placeholder="请输入项目名称" />
                </a-form-item>
              </template>
            </a-table-column>
            <a-table-column title="执行前照片">
              <template #default="text, params">
                <a-row type="flex" align="middle" :gutter="16">
                  <a-col flex="1">
                    <a-form-item hasFeedback :validate-status="params.photoBefore.length === '' ? 'warning' : ''">
                      <UploadImg v-model="params.photoBefore" :max="1" :showList="false" />
                    </a-form-item>
                  </a-col>
                  <a-col>
                    <viewer v-if="params.photoBefore.length" ref="photoBefore" :images="images">
                      <a-button type="link" @click="() => {
                        images = params.photoBefore
                        $refs.photoBefore.$viewer.show()
                      }">查看图片</a-button>
                      <template v-for="src in images">
                        <img :src="src.url" :key="src.url" v-show="false" />
                      </template>
                    </viewer>
                  </a-col>
                </a-row>
              </template>
            </a-table-column>
            <a-table-column title="执行后照片">
              <template #default="text, params">
                <a-row type="flex" align="middle" :gutter="16">
                  <a-col flex="1">
                    <a-form-item hasFeedback :validate-status="params.photoAfter.length === '' ? 'warning' : ''">
                      <UploadImg v-model="params.photoAfter" :max="1" :showList="false" />
                    </a-form-item>
                  </a-col>
                  <a-col>
                    <viewer v-if="params.photoAfter.length" ref="photoAfter" :images="images">
                      <a-button type="link" @click="() => {
                        images = params.photoAfter
                        $refs.photoAfter.$viewer.show()
                      }">查看图片</a-button>
                      <template v-for="src in images">
                        <img :src="src.url" :key="src.url" v-show="false" />
                      </template>
                    </viewer>
                  </a-col>
                </a-row>
              </template>
            </a-table-column>
            <a-table-column title="备注">
              <template #default="text, params">
                <a-form-item hasFeedback :validate-status="params.description === '' ? 'warning' : ''">
                  <a-textarea class="block" v-model="params.description" placeholder="请输入备注" :autosize="{ minRows: 1, maxRows: 1 }" />
                </a-form-item>
              </template>
            </a-table-column>
            <a-table-column title="操作" align="center">
              <template #default="text, params, index">
                <a @click="onDel(index)">删除</a>
              </template>
            </a-table-column>
            <template #footer>
              <a-button type="link" icon="plus" @click="onAdd">新增项目</a-button>
            </template>
          </a-table>
        </a-space>
      </a-col>
    </a-form-model>
  </a-modal>
</template>
<script>
// import { deviceModel } from '@/api/common'
// import storage from 'store'
// import { ACCESS_TOKEN } from '@/store/mutation-types'
import moment from 'moment'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    taskType: {
      type: Object,
      default: () => ({})
    }
  },
  model: {
    prop: 'visible',
    event: 'cancel'
  },
  components: {
    // CycleSelect: () => import('@/views/components/CycleSelect.vue')
    FoldForm: () => import('../../../components/FoldForm.vue')
  },
  data () {
    return {
      form: {
        devicePart: []
      },
      queryParam: {
        deviceModel: ''
      },
      tmpProjectList: {},
      formLoading: false,
      rules: {
        startTime: [{ required: true, message: '请选择执行时间' }],
        taskName: [{ required: true, message: '请输入任务名称' }],
        deviceCode: [{ required: true, message: '请选择设备编号' }],
        deviceModel: [{ required: true, message: '请选择设备型号' }],
        deviceName: [{ required: true, message: '请输入设备名称' }],
        executorName: [{ required: true, message: '请选择执行人' }],
        taskLevel: [{ required: true, message: '请选择优先级' }],
        projectName: [{ required: true, message: '请输入项目名称' }],
        description: [{ required: true, message: '请输入备注' }],
        photoBefore: [{ required: true, message: '请输入项目名称', type: 'array' }],
        photoAfter: [{ required: true, message: '请输入项目名称', type: 'array' }]
      },
      images: []
    }
  },
  methods: {
    onSubmit () {
      const tmpProjectList = JSON.parse(JSON.stringify(this.form.devicePart))
      // console.log(tmpProjectList)
      tmpProjectList.forEach(element => {
        element.photoAfter = element.photoAfter.length ? element.photoAfter[0].url : ''
        element.photoBefore = element.photoBefore.length ? element.photoBefore[0].url : ''
      })
      const val = tmpProjectList.every(item => {
        return item.photoAfter !== '' && item.photoBefore !== '' && item.description !== '' && item.projectName !== ''
      })
      if (val) {
        this.queryParam.tmpProjectList = tmpProjectList
        const {
          deviceCode = {},
          taskLevel = {},
          executorName = {},
          startTime = {},
          ...queryParam
        } = this.queryParam
        const paramsData = Object.assign(queryParam,
          this.taskType,
          { deviceCode: deviceCode.id },
          { taskLevel: taskLevel.id },
          { executorName: executorName.id },
          { startTime: startTime && moment(startTime).format('YYYY-MM-DD HH-MM-SS') })
        this.$refs.form.validate((valid, error) => {
          if (valid) {
            this.$http.post('/hb/tmpTask', paramsData).then(res => {
              if (res.code === 200) {
                this.form.devicePart = []
                this.queryParam = {}
                this.$message.success(res.msg)
                this.$emit('cancel', !this.visible)
                this.$emit('tableRefreshs')
              }
            })
          } else {
            this.$notification.destroy()
            this.$notification.error({
              message: '错误信息',
              description: '请填写信息'
            })
          }
        })
      } else {
        this.$message.error('请填写全部信息')
      }
    },
    onCancel () {
      this.form.devicePart = []
      this.queryParam = {}
      this.$emit('cancel', !this.visible)
    },
    // 上传图片
    customRequest (options, photoList) {
      /*       const params = new FormData()
            const fileName = options.file.name
            params.append('file', options.file)
            this.$http.post('/hb/attachment/deptAttachment/upload', params, {
              headers: { [ACCESS_TOKEN]: storage.get(ACCESS_TOKEN) }
            }).then(res => {
              const { code, fileSize, msg, url } = res
              if (code === 200) {
                this.$message.success('上传成功')
                photoList.splice(0, photoList.length)
                photoList.push({
                  uid: fileName,
                  name: fileName,
                  status: 'done',
                  url
                })
              } else {
                this.$notification.destroy()
                this.$notification.error({
                  message: '错误信息',
                  description: msg
                })
              }
            }) */
    },
    // 添加项目
    onAdd () {
      const row = {
        projectName: '',
        photoBefore: [],
        photoAfter: [],
        description: ''
      }
      // 判断上一项是否已填完
      // const flag = -1
      if (this.form.devicePart.length) {
        const last = [...this.form.devicePart].pop()
        const lastVal = Object.values(last)
        /*         flag = lastVal.findIndex((item, index) => {
                  if (index) return item === '' || []
                }) */
        const flag = lastVal.every(item => {
          return item !== '' && item.length !== 0
        })
        if (flag) {
          this.form.devicePart.push(row)
        } else {
          this.$message.destroy()
          this.$message.info('完成前一项才能继续添加')
        }
      } else {
        this.form.devicePart.push(row)
      }
    },
    // 删除项目
    onDel (index) {
      this.form.devicePart.splice(index, 1)
    },
    async deviceSelectChange (e) {
      // const { msg } = await deviceModel(e.label)
      // this.queryParam.deviceModel = msg
    }
  }
}
</script>
<style lang="scss" scoped>
.fold-form {
  /deep/ .ant-table {
    .ant-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
